/**
 * 
 */
package org.cst.ming.android.barcode.comminucation;


import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LogLevel;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;


public class MockServer
{
	// private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger("MockServer");
	private static final LoggingFilter LOGGING_FILTER = new LoggingFilter("MockServer");
	static
	{
		LOGGING_FILTER.setExceptionCaughtLogLevel(LogLevel.ERROR);
		LOGGING_FILTER.setSessionCreatedLogLevel(LogLevel.DEBUG);
		LOGGING_FILTER.setSessionOpenedLogLevel(LogLevel.DEBUG);
		LOGGING_FILTER.setSessionClosedLogLevel(LogLevel.DEBUG);
		LOGGING_FILTER.setMessageSentLogLevel(LogLevel.DEBUG);
		LOGGING_FILTER.setMessageReceivedLogLevel(LogLevel.DEBUG);
		LOGGING_FILTER.setSessionIdleLogLevel(LogLevel.DEBUG);
	}

	private final NioSocketAcceptor acceptor;

	private MockServer(int port, IoHandler handler)
			throws Exception
	{
		acceptor = new NioSocketAcceptor();
		final DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
		chain.addLast("eventLogging", LOGGING_FILTER);
		chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF8"))));

		acceptor.setHandler(handler);
		acceptor.bind(new InetSocketAddress(port));
	}

	public static MockServer start(int port, IoHandler handler)
			throws Exception
	{
		return new MockServer(port, handler);
	}
}
